package com.xjgc.webservice.server.realsap;

import com.alibaba.fastjson.JSON;
import com.xjgc.msibase.entity.MsiExoSystemServer;
import com.xjgc.msibase.entity.MsiServerRecord;
import com.xjgc.msibase.entity.MsiServerRecordInfo;
import com.xjgc.msibase.service.IMsiServerRecordInfoService;
import com.xjgc.msibase.service.IMsiServerRecordService;
import com.xjgc.msibase.service.IMsiServerTaskService;
import com.xjgc.msibase.vo.MsiServerTaskExoServer;
import com.xjgc.rest.ExoRestServerCall;
//import com.xjgc.webservice.ExoWebServiceUtils;
import com.xjgc.webservice.XParam;
import com.xjgc.webservice.XmlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;

import javax.annotation.Resource;
import javax.jws.WebService;
import java.util.Date;

/**
 * @author: 小逗号
 * @date: 2023/8/9
 * @description:
 * @since:
 */
@Slf4j
@WebService(name = "SapToMsiReal", targetNamespace = "http://service.ws.xjgc.SapToMsiReal.com/", endpointInterface = "com.xjgc.webservice.server.realsap.SapToMsiReal")
public class SapToMsiRealImpl implements SapToMsiReal {
    private static final String SOURCE_SYSTEM = "SAP";
    private static final String SERVER_CODE = "SapToMsiReal";

    /**
     * 中间库服务接口任务
     */
    @Resource
    private IMsiServerTaskService msiServerTaskService;

    /**
     * 中间库记录
     */
    @Resource
    private IMsiServerRecordService msiRealRecordService;
    /**
     * 中间库记录明细
     */
    @Resource
    private IMsiServerRecordInfoService msiServerRecordInfoService;

    @Resource
    private ExoRestServerCall exoRestServerCall;

    @Override
    public String realReceive(String taskCode, String serialNumber, String dataXml, String arg3) {
        //来源系统
        String sourceSystem = (StringUtils.isEmpty(arg3) || "1-1".equals(arg3)) ? SOURCE_SYSTEM : arg3;
        log.info("中间库服务[SapToMsiReal#realReceive]接收到{}系统==>任务[{}],流水号:{}", sourceSystem, taskCode, serialNumber);
        log.info("中间库服务[SapToMsiReal#realReceive]接收到{}系统==>任务[{}],流水号:{},xml:{}", sourceSystem, taskCode, serialNumber, dataXml);
        MsiServerTaskExoServer task = msiServerTaskService.getTaskExoServer(SERVER_CODE, taskCode);
        if (task == null) {
            String message = "中间库任务[" + taskCode + "],尚未上线!";
            log.warn(message);
            return XmlUtils.toXml(SapToMsiRealVO.error(message));
        }
        if (StringUtils.isBlank(task.getExoServerCode())) {
            log.warn("任务:" + task.getTaskCode() + ",未配置分发任务.直接返回成功!");
            return XmlUtils.toXml(SapToMsiRealVO.ok("中间库未配置分发任务.直接返回成功!"));

        }

        //检查流水号
        MsiServerRecord record = new MsiServerRecord(SERVER_CODE, taskCode, serialNumber, sourceSystem);
        MsiServerRecord msiRealRecord = msiRealRecordService.getById(record.getId());
        //流水号已存在.
        if (msiRealRecord != null) {
            if (StringUtils.isNotBlank(msiRealRecord.getResponseText())) {
                log.warn("流水号[{}]已存在,直接返回对应处理结果!", record.getId());
                return msiRealRecord.getResponseText();
            }
            log.warn("流水号[{}]已存在,任务处理中...", record.getSerialNo());
            return XmlUtils.toXml(SapToMsiRealVO.error("流水号[" + record.getSerialNo() + "]已存在,任务处理中..."));
        }

        //新流水号,新增中间库任务记录
        log.info("新流水号[{}],新增中间库任务记录", record.getSerialNo());
        msiRealRecordService.addRecord(record, dataXml);
        //中间库任务处理
        SapToMsiRealVO backVo = this.realReceive(task, record);
        String backXml = XmlUtils.toXml(backVo);
        log.info("新流水号[{}],更新中间库任务记录,中间库响应文本!", record.getSerialNo());
        msiRealRecordService.updateResponse(record, backXml);
        return backXml;

    }


    private SapToMsiRealVO realReceiveTest(MsiServerTaskExoServer task, MsiServerRecord record) {
        String requestXml = record.getRequestText();
        String paramClass = task.getParamClass();
        XParam xParam = null;
        try {
            xParam = XmlUtils.fromXml(record, paramClass, requestXml);
            msiServerRecordInfoService.add(record.getId(), new Date(), MsiServerRecordInfo.Node.PARSE_XML);
        } catch (Exception e) {
            msiServerRecordInfoService.add(record.getId(), new Date(), MsiServerRecordInfo.Node.PARSE_XML, "xml解析失败!");
            log.error(record.getId() + "xml解析失败!", e);
            return SapToMsiRealVO.error("xml解析失败!");
        }
        JSON json = xParam.dataAsJson();
        return SapToMsiRealVO.ok("xml解析成功:" + JSON.toJSONString(json));
    }

    private SapToMsiRealVO realReceive(MsiServerTaskExoServer task, MsiServerRecord record) {
        //分发任务调用WebService服务
        if (MsiExoSystemServer.WEBSERVICE.equals(task.getExoServerType())) {
            return this.zfWs(task, record);
        } else if (MsiExoSystemServer.REST.equals(task.getExoServerType())) {
            SapToMsiRealVO vo = null;
            //分发任务调用Rest服务
            Result result = this.zfRest(task, record);
            //todo 解析json,并返回xml
            if (result.isSuccess()) {
                vo = SapToMsiRealVO.ok(JSON.toJSONString(result.getResult()));
            } else {
                vo = SapToMsiRealVO.error(result.getMessage());
            }
            return vo;
        } else {
            return SapToMsiRealVO.error("分发任务配置错误!");
        }
    }

    /**
     * 转发WS
     *
     * @param task
     * @param record
     * @return
     */
    private SapToMsiRealVO zfWs(MsiServerTaskExoServer task, MsiServerRecord record) {
        String requestXml = record.getRequestText();
        //WebService服务名
        String webService = task.getWebService();
        String wsTask = StringUtils.isBlank(task.getConstant()) ? webService : webService + "[" + task.getConstant() + "]";
        log.info("WebService分发任务==>[{}]", wsTask);
        msiServerRecordInfoService.add(record.getId(), new Date(), MsiServerRecordInfo.Node.ZF_WS, wsTask, requestXml);
        try {
//            String response = ExoWebServiceUtils.call(webService, task.getConstant(), "MSI" + System.currentTimeMillis(), requestXml);
//            msiServerRecordInfoService.add(record.getId(), new Date(), MsiServerRecordInfo.Node.ZF_WS_RES, wsTask, response);
//            return SapToMsiRealVO.ok(response);
            return SapToMsiRealVO.ok();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("转发WebService失败,", e);
            return SapToMsiRealVO.error("转发WebService失败!");
        }
    }

    /**
     * 转发Rest
     *
     * @param task
     * @param record
     * @return
     */
    private Result zfRest(MsiServerTaskExoServer task, MsiServerRecord record) {
        String requestXml = record.getRequestText();
        String paramClass = task.getParamClass();
        //解XML,并提取JSON
        XParam xParam = null;
        try {
            xParam = XmlUtils.fromXml(record, paramClass, requestXml);
            msiServerRecordInfoService.add(record.getId(), new Date(), MsiServerRecordInfo.Node.PARSE_XML);
        } catch (Exception e) {
            msiServerRecordInfoService.add(record.getId(), new Date(), MsiServerRecordInfo.Node.PARSE_XML, "xml解析失败!");
            log.error(record.getId() + "xml解析失败!", e);
            return Result.error("xml解析失败!");
        }
        JSON json = xParam.dataAsJson();
        msiServerRecordInfoService.add(record.getId(), new Date(), MsiServerRecordInfo.Node.TO_JSON);
        log.info("提取dataAsJson ==> {}", json);
        Result result = exoRestServerCall.requestExoServer(record.getId(), task, json);
        return result;
    }

}
